/*
 * @LastEditTime: 2023-03-31 23:33:10
 * @Method: 
 * @Description: 
 */
import java.util.*;

package CodeTop;

public class Solution47 {
    List<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>();
    boolean[] used;

    public List<List<Integer>> permuteUnique(int[] nums) {
        used = new boolean[nums.length];
        Arrays.sort(nums);
        dfs(nums);
        return res;
    }

    public void dfs (int[] nums) {
        if (path.size() > nums.length) {
            return;
        }
        if (path.size() == nums.length) {
            res.add(new LinkedList<>(path));
            return;
        }
        for (int i = 0;i < nums.length;i++) {
            if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) {
                continue;
            }
            if (used[i]) {
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            dfs(nums);
            used[i] = false;
            path.removeLast();
        }
    }
}
